package cn.com.utt.gateway.controller;

import java.security.Principal;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;

import cn.com.utt.common.service.TableService;
import cn.com.utt.common.vo.CustomColumn;
import cn.com.utt.common.vo.RestResult;
import cn.com.utt.common.vo.TableCustomColumn;
import cn.com.utt.common.vo.User;

@RestController
@RequestMapping("/v1/tables")
public class TableController {

	@Autowired
	private TableService tableService;
	

	/*
	 * {"columns":[{"column":"name","order":1},{"column":"sn","order":2}],
	 * "tableName":"devices"}
	 */
	//@PreAuthorize("hasRole('admin')")
	@RequestMapping(value = "/customColumn", method = { RequestMethod.POST }, consumes = "application/json")
	public Map<String, Object> updteCustomColumn(@RequestBody TableCustomColumn customColumn,Principal principal) {
		RestResult result = new RestResult();
		System.out.println(JSON.toJSONString(customColumn));
		Authentication authentication = (Authentication) principal;
		User user = (User)authentication.getPrincipal();
		tableService.updateCustomColumn(customColumn, user.getId());
		return result.toJsonObject();
	}
	
	@RequestMapping(value = "/customColumn/{table}", method = { RequestMethod.GET })
	public Map<String, Object> queryCustomColumn(@PathVariable String table,Principal principal) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User)authentication.getPrincipal();
		List<CustomColumn> customColumns = tableService.queryCustomColumnByTable(table, user.getId());
		result.put("columns", customColumns);
		return result.toJsonObject();
	}
}
